import { Message } from "element-ui";
import { Ref, ref } from "vue";

export const usePagination = (
  queryParams: any,
  request: any,
  engThInit?: Array<any>,
  filterId?: string
) => {
  const dataTable = ref([]);
  const tableLoading = ref(false);
  const engTh: Ref<Array<string | null>> = ref(engThInit || []);
  let pageInfo = ref({
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    count: 0,
  });
  const pageSizeChange = (v: number) => {
    console.log("条数", v);
    pageInfo.value.pageSize = v;
    pageInfo.value.pageIndex = 1;
    selectData();
  };
  const selectData = async (v?: number) => {
    if (v) {
      pageInfo.value.pageIndex = v;
    }
    console.log("页数", pageInfo.value.pageIndex);
    queryParams.value.pageIndex = pageInfo.value.pageIndex;
    queryParams.value.pageSize = pageInfo.value.pageSize;
    tableLoading.value = true;
    const res: any = await request(queryParams.value);
    if (res && res.data) {
      const { records, count, pageIndex, pageSize } = res.data;
      dataTable.value = records;
      console.log("res", res.data, "dataTable", dataTable.value);
      if (records.length > 0) {
        engTh.value = Object.keys(records[0]);
        engTh.value = engTh.value.filter((item) => item !== "transactionId");
        if (filterId) {
          engTh.value = engTh.value.filter((item) => item !== filterId);
        }
      }
      pageInfo.value.total = parseInt(count);
      pageInfo.value.pageIndex = parseInt(pageIndex);
      pageInfo.value.pageSize = parseInt(pageSize);
      tableLoading.value = false;
    } else {
      Message.error("数据获取失败!");
      tableLoading.value = false;
    }

    console.log("数据", res.data, engTh.value, pageInfo.value);
  };
  return {
    dataTable,
    engTh,
    pageInfo,
    pageSizeChange,
    selectData,
    tableLoading,
  };
};
